//
//  WMPhoto.m
//  WeightMaster
//
//  Created by sungeo on 15/8/29.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "WMPhoto.h"

NSString * const WMPhotoRecord = @"PhotoRecord";

static NSString * const WMPhotoUUID = @"PhotoUUID";
static NSString * const WMPhotoImage = @"PhotoImage";

@implementation WMPhoto{
    UIImage * _image;
}

- (instancetype)init{
    if (self = [super init]) {
        _UUID = [NSUUID UUID].UUIDString;
        _isUploaded = @(NO);
        _isDownloaded = @(NO);
    }
    
    return self;
}

- (CKRecord *)iCloudRecord{
    CKRecordID * recordID = [[CKRecordID alloc] initWithRecordName:_UUID];    
    CKRecord * record = [[CKRecord alloc] initWithRecordType:WMPhotoRecord recordID:recordID];
    
    // iCloud 上只用存储 UUID 和图片内容
    
    // UUID
    record[WMPhotoUUID] = _UUID;
    
    // 图片
    CKAsset * asset = [[CKAsset alloc] initWithFileURL:[[self class] localImageURLForUUID:_UUID]];
    record[WMPhotoImage] = asset;
    
    return record;
}

- (void)setImage:(UIImage *)image{
    _image = image;
    
    if (_UUID.length == 0) {
        _UUID = [NSUUID UUID].UUIDString;
    }
    
    // 生成照片路径，并保存照片到本地缓存
    NSURL * localDir = [[self class] localImageURLForUUID:_UUID];
    NSData * data = UIImageJPEGRepresentation(_image, 0.3);
    NSLog(@"照片大小：%@ K", @(data.length / 1024));
    [data writeToURL:localDir atomically:YES];
}

- (UIImage *)updateImageWithCKRecord:(CKRecord *)record{
    if (record == nil) {
        return nil;
    }
    
    CKAsset * asset = record[WMPhotoImage];
    if (asset == nil) {
        return nil;
    }
    
    self.image = [UIImage imageWithContentsOfFile:asset.fileURL.path];
    
    return _image;
}


+ (NSURL *)localImageURLForUUID:(NSString *)UUID{
    NSURL * documentDirectory = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
    
    NSString * temporaryName = [UUID stringByAppendingString:@".jpeg"];
    
    return [documentDirectory URLByAppendingPathComponent:temporaryName];
}

- (BOOL)deleteLocalPhoto{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    NSURL * localURL = [[self class] localImageURLForUUID:_UUID];
    
    if ([fileManager fileExistsAtPath:localURL.path]) {
        NSError * error = nil;
        if( ![fileManager removeItemAtURL:localURL error:&error] ){
            NSLog(@"删除本地文件失败：%@", error);
        }else{
            return YES;
        }
    }else{
        NSLog(@"要删除的本地文件不存在");
    }
    
    // TODO: 删除失败时怎么处理？
    
    return NO;
}


@end
